//
//  ViewController.swift
//  coredata使用
//
//  Created by xuNick on 16/11/9.
//  Copyright © 2016年 NN. All rights reserved.
//

import UIKit
import CoreData

class EarthQuakeList: UIViewController {
    
    @IBOutlet weak var displayView: UITableView!
//    let context = CoredataManager.managedObjectContext
    var data: [Quake] = [] {
        didSet{
            displayView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        displayView.dataSource = self
        displayView.register( UINib(nibName: "ListCellTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        displayView.rowHeight = 60
        displayView.separatorStyle = .singleLine
        displayView.separatorColor = UIColor.white
        
    }
    func fetchData() {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Quake")
        let entity:NSEntityDescription = NSEntityDescription.entity(forEntityName: "Quake", in: CoredataManager.managedObjectContext)!
        request.entity = entity
        do {
            data = try CoredataManager.managedObjectContext.fetch(request) as! [Quake]
            print(data.count)
        }catch{
            print("错了")
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.fetchData()
    }

}


//MARK: - tableviewDatasource
extension EarthQuakeList: UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ListCellTableViewCell
        cell.model = data[indexPath.row]
        return cell
    }
    
}

